<style lang="scss" scoped>
@import "./main.scss";
</style>

<template>
  <div class="main">
    <div class="sidebar-menu-con menu-bar">
      <div class="logo-con">
        <img :src="storeSideLogo" key="max-logo" />
      </div>
      <shrinkable-menu></shrinkable-menu>
    </div>

    <Modal
           title="自动发货设置"
           v-model="modalVisible"
           :mask-closable="false"
           :width="700"
    >
      <Form ref="form" :label-width="100">
        <FormItem label="物流" prop="logisticses" style="width:90%;">
          <div style="display: flex;flex-wrap: wrap;" >
            <div v-for="item in deliver.logisticsList"  @click="logisticsItemFun(item)">
              <span v-if="item.selected==='1'" style="color:white;background-color:green;padding:5px 10px;margin:5px;border-radius: 5px;cursor: pointer">{{item.name}}</span>
              <span v-else style="background-color:rgba(201,197,197,0);padding:5px 10px;margin:5px;border-radius: 5px;cursor: pointer">{{item.name}}</span>
            </div>
          </div>
          <span style="color: red;margin-top: 10px;">默认从可用物流列表随机选择一个物流发货</span>

        </FormItem>
        <FormItem label="已选择物流" prop="printer" hidden>
          <span style="color: red" v-if="deliver.logistics===''">请选择物流</span>
          <span v-else>{{deliver.logistics}}</span>
        </FormItem>
        <FormItem label="打印机" prop="printer" style="width:90%;">
          <Select @on-change="" v-model="deliver.printer" >
            <Option v-for="item in deliver.printerList" :key="item.index" :value="item.name" >{{ item.name }}
            </Option>
          </Select>
        </FormItem>
        <FormItem label="延迟发货" prop="printer" style="width:90%;">
          <Select @on-change="" v-model="deliver.delaySecond" >
            <Option v-for="item in delaySecondList" :key="item.index" :value="item.value" >{{ item.description }}
            </Option>
          </Select>
          <span>延迟发货表示订单支付后,自动发货会根据这个时间延迟多长时间发货</span>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button v-if="deliver.status==='open'" type="primary" @click="cacelFaceAuto">取消自动</Button>
        <Button v-else type="primary"  @click="startFaceAuto">开启自动</Button
        >
      </div>
    </Modal>
    <Modal
      title="自动打票设置"
      v-model="receiveModalVisible"
      :mask-closable="false"
      :width="700"
    >
      <Form ref="form" :label-width="100">
        <FormItem label="打印机" prop="printer" style="width:90%;">
          <Select @on-change="" v-model="receive.printer" >
            <Option v-for="item in receive.printerList" :key="item.index" :value="item.name" >{{ item.name }}
            </Option>
          </Select>
        </FormItem>
        <FormItem label="延迟打票" prop="printer" style="width:90%;">
          <Select @on-change="" v-model="receive.delaySecond" >
            <Option v-for="item in delaySecondList" :key="item.index" :value="item.value" >{{ item.description }}
            </Option>
          </Select>
          <span>延迟打票表示订单支付后,自动打票会根据这个时间延迟多长时间打印小票,防止中途退单(即小票打出来了订单又退了)</span>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button v-if="receive.status==='open'" type="primary" @click="cacelFaceAuto">取消自动</Button>
        <Button v-else type="primary"  @click="startFaceAuto">开启自动</Button
        >
      </div>
    </Modal>

    <!-- 顶部标题栏主体 -->
    <div class="main-header-con" :style="{ height: setting.isUseTabsRouter ? '100px' : '60px' }">
      <div class="main-header">
        <div
          class="header-avator-con"
        >
          <!-- 左侧栏 -->
          <div style="display: flex;align-items: center;">
<!--              <div class="auto-btn" @click="showOrderDeliverModal2">-->
<!--                <div style="padding: 7px">自动打票已开启(已接0单)</div>-->
<!--                <Icon type="ios-arrow-forward" style="color: white;font-size: larger;padding-right: 5px"/>-->
<!--              </div>-->
<!--              <div :style="autoFaceClass" class="auto-btn" @click="showOrderDeliverModal">-->
<!--                <div style="padding: 7px">{{autoFaceBtn}}</div>-->
<!--                <Icon type="ios-arrow-forward" style="color: white;font-size: larger;padding-right: 5px"/>-->
<!--              </div>-->
          </div>
          <!-- 用户头像 -->
          <div class="user-dropdown-menu-con">
            <Row
              type="flex"
              justify="end"
              align="middle"
              class="user-dropdown-innercon"
            >
<!--             <span style="font-size: 16px;font-weight: 500">语音播报</span> <i-switch v-model="isVoice" @on-change="openVoice" style="margin:0px 10px;"></i-switch>-->
              <ul class="nav-list">
                <li class="nav-item " @click="handleClickSetting">
                  <Tooltip content="设置">
                    <Icon size="16" type="md-settings" />
                  </Tooltip>
                </li>
              </ul>
              <Dropdown
                transfer
                trigger="hover"
                @on-click="handleClickUserDropdown"
              >
                <div class="dropList">

                  <Avatar
                    icon="ios-person"
                    :src="userInfo.storeLogo"
                    style="background: #fff; margin-left: 10px"
                  ></Avatar>
                </div>
                <DropdownMenu slot="list">
                  <DropdownItem name="changePass">修改密码</DropdownItem>
                  <DropdownItem name="loginOut" divided>退出</DropdownItem>
                </DropdownMenu>
              </Dropdown>
            </Row>
          </div>
        </div>
      </div>
      <!-- 已打开的页面标签 -->
      <div class="tags-con" v-if="setting.isUseTabsRouter">
        <tags-page-opened :pageTagsList="pageTagsList"></tags-page-opened>
      </div>
    </div>
    <div class="single-page-con" :style="{ 'top': setting.isUseTabsRouter ? '100px' : '60px', height: setting.isUseTabsRouter ? 'calc(100% - 110px)' : 'calc(100% - 70px)' }">
      <div class="single-page">
        <!-- <keep-alive :include="cachePage"> -->
        <!-- </keep-alive> -->
        <keep-alive>
          <router-view v-if="$route.meta.keepAlive"></router-view>
        </keep-alive>
        <router-view v-if="!$route.meta.keepAlive"></router-view>
      </div>
    </div>
    <!-- 全局加载动画 -->
    <circleLoading class="loading-position" v-show="loading" />
    <!-- 右侧抽屉配置 -->
    <configDrawer ref="config"/>
  </div>
</template>

<script>
import shrinkableMenu from "./main-components/shrinkable-menu/shrinkable-menu.vue";
import tagsPageOpened from "./main-components/tags-page-opened.vue";
import circleLoading from "@/views/my-components/lili/circle-loading.vue";
import configDrawer from "@/views/main-components/config-drawer.vue";

import Cookies from "js-cookie";
import util from "@/libs/util.js";
import { logout } from "@/api/index";
import {getUPrintOrderList, updateSendoutSetting} from "@/api/order";
import { getUsePrinter } from "@/api/shops";
import {getPrinterList, printByName, printOneByName} from "@/utils/lodop";
import * as API_Order from "@/api/order";
const config = require("@/config/index.js");
export default {
  components: {
    shrinkableMenu,
    tagsPageOpened,
    circleLoading,
    configDrawer,
  },
  data() {
    return {
      config,
      sliceNum: 5, // 展示nav数量
      userInfo: {}, // 用户信息
      storeSideLogo: "", //logo图片
      isVoice:true,
      modalVisible: false,
      autoFaceClass:"background-color:red",
      autoFaceBtn:"自动发货未开启",
      //批量发货
      deliverForm:{},
      deliver:{
        num:0,
        logisticsList: [],
        printerList:[],
        printer:"",
      },
      //自动打印小票设置
      receiveModalVisible:false,
      autoReceiveClass:"background-color:red",
      autoReceiveBtn:"自动打印小票设置",
      receive:{},
      delaySecondList:[
        {
          value:60,
          description:'延迟1分钟'
        },
        {
          value:300,
          description:'延迟5分钟'
        },
        {
          value:600,
          description:'延迟10分钟'
        },
        {
          value:1800,
          description:'延迟30分钟'
        },
        {
          value:3600,
          description:'延迟1小时'
        },
        {
          value:10800,
          description:'延迟3小时'
        }
      ]
    };
  },
  computed: {
    setting(){
      let data = this.$store.state.setting

      return data.setting
    },
    loading() {
      return this.$store.state.app.loading;
    },
    pageTagsList() {
      return this.$store.state.app.storeOpenedList; // 打开的页面的页面对象
    },
    cachePage() {
      return this.$store.state.app.cachePage;
    },
    lang() {
      return this.$store.state.app.lang;
    },
    mesCount() {
      return 0;
    },
  },
  methods: {
    saveFaceSetting(){
      if (this.deliverForm.id){
        API_Order.updateSendoutSetting(this.deliverForm).then((res) => {
          if (res.success) {
            this.deliverForm=this.deliver = res.result;
            this.headFaceBtnStyleUpdate(this.deliver.status);
          }
        });
      }else {
        API_Order.saveSendoutSetting(this.deliverForm).then((res) => {
          if (res.success) {
            this.deliverForm=this.deliver = res.result;
            this.headFaceBtnStyleUpdate(this.deliver.status);
          }
        });
      }
    },
    startFaceAuto(){
      if (this.deliver.logistics ===""){
        this.$Message.warning("请选择物流");
        return;
      }
      if (this.deliver.printer===""){
        this.$Message.warning("请选择打印机");
        return;
      }
      let pram ={
        id:this.deliver.id,
        status:'open'
      }
      API_Order.updateSendoutSetting(pram).then((res) => {
        if (res.success) {
          this.deliver.status=res.result.status;
          this.headFaceBtnStyleUpdate(this.deliver.status);
        }
      });
    },
    headFaceBtnStyleUpdate(status){
      if (status==="open"){
        this.autoFaceBtn="自动发货已开启";
        this.autoFaceClass="background-color:green";
      }else {
        this.autoFaceBtn="自动发货未开启";
        this.autoFaceClass="background-color:red";
      }
    },
    cacelFaceAuto(){
      let pram ={
        id:this.deliver.id,
        status:'close'
      }
      API_Order.updateSendoutSetting(pram).then((res) => {
        if (res.success) {
            this.deliver.status=res.result.status;
            this.headFaceBtnStyleUpdate(this.deliver.status);
        }
      });
    },
    showOrderDeliverModal(){
      //查询发货设置
      API_Order.getStoreSendoutSetting("auto").then((res) => {
        console.log(res)
        if (res.success) {
          this.deliverForm=this.deliver = res.result;
          //获取打印机
          this.deliver.printerList = getPrinterList();
          this.deliver.num=this.deliver.orderList.length;
          this.modalVisible=true;
        }
      });
    },
    showOrderDeliverModal2(){
      //查询接单设置
      API_Order.getStoreReceivingSetting("auto").then((res) => {
        if (res.success) {
          this.receive = res.result;
          //获取打印机
          this.receive.printerList = getPrinterList();
          this.receive.num=this.receive.orderList.length;
          this.receiveModalVisible=true;
        }
      });
    },

    //自动打印和播报
    autoPrintAndVoice(){
      //查询发货配置
      // API_Order.getStoreSendoutSetting("auto").then((res) => {
      //   if (res.success) {
      //     //console.log(res);
      //     this.headFaceBtnStyleUpdate(res.result.status);
      //   }
      // });
      //每5秒执行一次
      setInterval(function(){
        //查询发货设置
        API_Order.getStoreSendoutSetting("auto").then((res) => {
          if (res.success) {
            //console.log(res);
            let data = res.result;
            if (data.orderList.length>0){
              //播放语音
            }
            if (data.orderList.length>0 && data.status==="open"){
              //自动批量发货
              API_Order.batchFaceDelivery(data).then((res) => {
                if (res.success) {
                  let printer = res.result.printer;
                  res.result.orderList.forEach(function (item,index) {
                    //打印电子面单
                    printOneByName(printer,item.printTemplate)
                  });
                }
              });
            }
          }
        });
      },5000);

    },
    openVoice(val){
      console.log(val)
    },

    logisticsItemFun(item){
      if (item.selected==="1"){
        item.selected="0"
      }else {
        item.selected="1"
      }
      this.deliver.logistics="";
      for (let i = 0; i < this.deliver.logisticsList.length; i++) {
        if (this.deliver.logisticsList[i].selected==="1"){
          if (this.deliver.logistics === ""){
            this.deliver.logistics +=this.deliver.logisticsList[i].logisticsId;
          }else {
            this.deliver.logistics +=","+this.deliver.logisticsList[i].logisticsId;
          }
        }
      }
    },



    handleClickSetting() {
      this.$refs.config.open();
    },
    // 初始化方法
    init() {
      // 菜单
      let pathArr = util.setCurrentPath(this, this.$route.name);
      if (pathArr.length >= 2) {
        this.$store.commit("addOpenSubmenu", pathArr[1].name);
      }
      this.storeSideLogo = localStorage.getItem("sellerlogoImg");
      window.document.title = localStorage.getItem("sellersiteName");
      //动态获取icon
      let link =
        document.querySelector("link[rel*='icon']") ||
        document.createElement("link");
      link.type = "image/x-icon";
      link.href = localStorage.getItem("sellerIconImg");
      link.rel = "shortcut icon";
      document.getElementsByTagName("head")[0].appendChild(link);

      let userInfo = JSON.parse(Cookies.get("userInfoSeller"));
      this.userInfo = userInfo;
      this.checkTag(this.$route.name);

      let currWidth = document.body.clientWidth;
      if (currWidth <= 1200) {
        this.sliceNum = 2;
      }
    },
    // 用户头像下拉
    handleClickUserDropdown(name) {
      if (name == "ownSpace") {
        util.openNewPage(this, "personal-enter");
        this.$router.push({
          name: "personal-enter",
        });
      } else if (name == "changePass") {
        util.openNewPage(this, "change_pass");
        this.$router.push({
          name: "change_pass",
        });
      } else if (name == "loginOut") {
        logout().then(res => {
          Cookies.set("accessToken", "");
          this.$store.commit("logout", this);
          this.$store.commit("clearOpenedSubmenu");
          this.setStore("accessToken", "");
          this.setStore("refreshToken", "");
          this.$router.push({ path: "/login" });
        })
      }
    },
    // 快捷页签选中状态
    checkTag(name) {
      let openpageHasTag = this.pageTagsList.some((item) => {
        if (item.name == name) {
          return true;
        }
      });
      if (!openpageHasTag) {
        //  解决关闭当前标签后再点击回退按钮会退到当前页时没有标签的问题
        util.openNewPage(
          this,
          name,
          this.$route.params || {},
          this.$route.query || {}
        );
      }
    },
    // 宽度变化
    resize() {
      let currWidth = document.body.clientWidth;
      let count = currWidth / 300;
      if (count > 6) {
        this.sliceNum = 6;
      } else {
        this.sliceNum = count;
      }
    },
  },
  watch: {
    $route(to) {
      this.$store.commit("setCurrentPageName", to.name);
      let pathArr = util.setCurrentPath(this, to.name);
      if (pathArr.length > 2) {
        this.$store.commit("addOpenSubmenu", pathArr[1].name);
      }
      this.checkTag(to.name);
      localStorage.currentPageName = to.name;
    },
    lang() {
      util.setCurrentPath(this, this.$route.name); // 在切换语言时用于刷新面包屑
    },
  },


  mounted() {
    this.init();
    let that = this;
    this.resize();
    window.addEventListener("resize", function () {
      that.resize();
    });
    //this.autoPrintAndVoice();
  },
  created() {
    // 显示打开的页面的列表
    this.$store.commit("setOpenedList");
  },
};
</script>
<style lang="scss" scoped>
.auto-btn{
  display: flex;
  text-align: center;
  align-items: center;
  justify-content: center;
  background-color: #999;
  color: white;
  border-radius: 5px;
  cursor: pointer;
  margin-right: 10px;
}
.auto-face{
  display: flex;
  text-align: center;
  align-items: center;
  justify-content: center;
  background-color: #999;
  color: white;
  border-radius: 5px;
  cursor: pointer;
  margin-right: 10px;
}

</style>
